package game;

import java.util.List;
import java.util.Random;

import org.newdawn.slick.GameContainer;

import sound.SoundManager;
import util.Vector2D;

import entities.Enemy;

public class DelayedSpawnWave extends EnemyWave {

	private static Random random = new Random();
	private int numberOfEnemies;					// number of enemies spawned at the same time
	private int spawnTime;
	private int timer;
	private int ind;

	public DelayedSpawnWave(List<Enemy> enemies, int numberOfEnemies, int minDelay, int addDelay) {
		super(enemies);
		this.numberOfEnemies = numberOfEnemies;
		spawnTime = minDelay + random.nextInt(addDelay);
		timer = spawnTime;
		ind = 0;
	}

	@Override
	public boolean isDefeated() {
		for (Enemy e : enemies) {
			if (level.isActive(e))
				return false;
		}
		if (ind >= enemies.size()) {
			return true;
		}
		return false;
	}

	@Override
	public void update(GameContainer gc, int delta) {
		timer += delta;
		if (ind < enemies.size()) {
			if (timer > spawnTime) {
				for (int i = 0; i < numberOfEnemies; i++) {
					System.out.println("!");
					try {
						Enemy e = enemies.get(ind);
						Vector2D pos = new Vector2D(gc.getWidth() - e.getImage().getWidth(),
								random.nextInt(gc.getHeight() - e.getImage().getHeight()));
						e.spawn(level, pos);
						ind++;
						System.out.println("Enemy spawned!");
					} catch (IndexOutOfBoundsException e) {
						break;
					}
				}
				timer = 0;
			}
		}

	}

	@Override
	public void reset() {
		for (Enemy e : enemies) {
			e.reset();
		}
		ind = 0;
		SoundManager.getSoundManager().playMusic(SoundManager.mainTheme);
	}
}
